package com.sdy.supermarket.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.approval.biz.model.TpApproveFlow;
import com.sdy.approval.biz.model.TpOrder;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.supermarket.biz.mapper.GsAppMapper;
import com.sdy.supermarket.biz.mapper.GsIpChangeMapper;
import com.sdy.supermarket.biz.model.*;
import com.sdy.supermarket.biz.mapper.GsAppIpApplyMapper;
import com.sdy.supermarket.biz.param.IpApplyListParam;
import com.sdy.supermarket.biz.service.GsAppIpApplyService;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.supermarket.biz.service.GsAppService;
import com.sdy.supermarket.biz.service.GsIpChangeService;
import com.sdy.supermarket.biz.service.GsResService;
import com.sdy.supermarket.biz.utils.PageUtils;
import com.sdy.supermarket.biz.vo.IpApplyInfoVo;
import com.sdy.supermarket.biz.vo.IpApplyListVo;
import com.sdy.supermarket.biz.vo.OrderFlowVO;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.DeptDto;
import com.sdy.usercenter.api.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hyh
 * @since 2019-08-01
 */
@Slf4j
@Service
public class GsAppIpApplyServiceImpl extends BaseServiceImpl<GsAppIpApply> implements GsAppIpApplyService {
    @Resource
    private GsAppIpApplyMapper gsAppIpApplyMapper;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private GsAppService gsAppService;
    @Autowired
    private GsIpChangeService gsIpChangeService;
    @Autowired
    private ApprovalAllApi approvalAllApi;
    @Autowired
    private GsResService gsResService;


    @Override
    public IPage<IpApplyListVo> getUserApplyList(Integer userId, long size, long current, String name, String ip, Integer state) {
        if (null != state && state == 2) {
            state = 3;
        }
        UserDTO user = userQueryApi.getUser(userId);
        IpApplyListParam param = new IpApplyListParam().setUserId(userId).setDeptId(user.getOwnDeptId()).setSize(current * size).setCurrent((current - 1) * size).setName(name).setIp(ip).setState(state);
        List<IpApplyListVo> userIpApplyList = gsAppIpApplyMapper.getUserIpApplyList(param);
        // 获取列表数据所有的ipID,并查询到IP信息
        List<String> ipId = userIpApplyList.stream().map(managerApply -> managerApply.getIpId()).collect(Collectors.toList());
        StringBuilder ipIdList = new StringBuilder();
        ipId.forEach(id -> {
            ipIdList.append(id);
        });
        List<GsIpChange> ipChangeList = gsIpChangeService.list(Wrappers.<GsIpChange>lambdaQuery().in(GsIpChange::getId, Arrays.asList(new String(ipIdList).split(","))));
        // 对比订单列表的ID列表和ip修改表的ID，放入对应位置
        userIpApplyList.forEach(applyVo -> {
            ipChangeList.forEach(change -> {
                if (applyVo.getIpId().indexOf(change.getId() + "") != -1) {
                    applyVo.getIpList().add(change.getIp());
                    applyVo.setIpId(applyVo.getIpId().replace(change.getId() + "", ""));
                }
            });
        });
        userIpApplyList.forEach(userIpApp -> {
            userIpApp.setUserName(user.getName());
            userIpApp.setUserDept(user.getOwnDeptName());
        });
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("name", name);
        map.put("ip", ip);
        map.put("state", state);
        int total = gsAppIpApplyMapper.getUserIpApplyListTotal(map);
        IPage<IpApplyListVo> vo = new Page<>();
        vo.setTotal(total);
        vo.setSize(size);
        vo.setCurrent(current);
        vo.setPages(total + size - 1 / size);
        vo.setRecords(userIpApplyList);
        return vo;
    }

    @Override
    public IPage<IpApplyListVo> getManagerApproveIpApplyList(Integer userId, long size, long current, String name, String ip, Integer state) {
        if (null != state && state == 2) {
            state = 3;
        }
        IpApplyListParam param = new IpApplyListParam().setUserId(null).setDeptId(null).setSize(current * size).setCurrent((current - 1) * size).setName(name).setIp(ip).setState(state);
        IPage<IpApplyListVo> vo = new Page<>();
        UserDTO user = userQueryApi.getUser(userId);
        List<TpOrder> orders = approvalAllApi.selectTpOrderApprovalByCondition(user.getOwnDeptIdList(), user.getRoleIdList(), null, null, null, "[政务超市]");
        // 给参数类设置ID列表,根据审核流程模块提供的ID查询数据
        List<String> orderNoList = orders.stream().map(TpOrder::getApplicationNum).collect(Collectors.toList());
        if (!orderNoList.isEmpty()) {
            param.setIpOrderIdList(orderNoList);
        } else {
            return vo;
        }
        // 获取到查询的数据
        List<IpApplyListVo> managerApproveIpApplyList = gsAppIpApplyMapper.getUserIpApplyList(param);
        // 获取列表数据所有的ipID,并查询到IP信息
        List<String> ipId = managerApproveIpApplyList.stream().map(managerApply -> managerApply.getIpId()).collect(Collectors.toList());
        StringBuilder ipIdList = new StringBuilder();
        ipId.forEach(id -> {
            ipIdList.append(id);
        });
        List<GsIpChange> ipChangeList = gsIpChangeService.list(Wrappers.<GsIpChange>lambdaQuery().in(GsIpChange::getId, Arrays.asList(new String(ipIdList).split(","))));
        // 对比订单列表的ID列表和ip修改表的ID，放入对应位置
        managerApproveIpApplyList.forEach(applyVo -> {
            ipChangeList.forEach(change -> {
                if (applyVo.getIpId().indexOf(change.getId() + "") != -1) {
                    applyVo.getIpList().add(change.getIp());
                    applyVo.setIpId(applyVo.getIpId().replace(change.getId() + "", ""));
                }
            });
        });
        List<Integer> collect = managerApproveIpApplyList.stream().map(IpApplyListVo::getUserId).collect(Collectors.toList());
        if (!collect.isEmpty()) {
            List<UserDTO> userDTOS = userQueryApi.listUser(collect);
            managerApproveIpApplyList.forEach(userIpApp -> {
                userDTOS.forEach(userDTO -> {
                    if (userDTO.getId().equals(userIpApp.getUserId())) {
                        userIpApp.setUserName(userDTO.getName());
                        userIpApp.setUserDept(userDTO.getOwnDeptName());
                    }
                });
            });
        }
        // 给列表数据设置节点信息
        List<TpApproveFlow> newFlowInfo = approvalAllApi.selectApprovalFlowByNumOrderList(param.getIpOrderIdList(), user.getOwnDeptIdList(), user.getRoleIdList());
        newFlowInfo.forEach(flow -> {
            managerApproveIpApplyList.forEach(approveIpApply -> {
                if (approveIpApply.getApplyNo().equals(flow.getApplyId())) {
                    approveIpApply.setResult(flow.getResult());
                }
            });
        });
        Map<String, Object> map = new HashMap<>();
        map.put("ipOrderIdList", orders.stream().map(TpOrder::getApplicationNum).collect(Collectors.toList()));
        map.put("name", name);
        map.put("ip", ip);
        map.put("state", state);
        map.put("userId", null);
        int total = gsAppIpApplyMapper.getUserIpApplyListTotal(map);
        vo.setTotal(total);
        vo.setSize(size);
        vo.setCurrent(current);
        vo.setPages(total + size - 1 / size);
        // TODO 此处查询出了所有数据，对数据进行‘假’分页
        PageUtils<IpApplyListVo> pageData = new PageUtils(size, current, managerApproveIpApplyList);
        vo.setRecords(pageData.getRecords());
        return vo;
    }

    @Override
    public void ipApprove(Integer userId, Integer result, String remark, String ipApplyNo) throws Exception {
        Assert.isTrue(null == result || null == remark, "参数错误");
        UserDTO user = userQueryApi.getUser(userId);
        if (result == 2 || result == 3) {
            TpApproveFlow tpflow = new TpApproveFlow();
            tpflow.setResult(result);
            //   ApplyId
            tpflow.setApplyId(ipApplyNo);
            tpflow.setUserId(userId);
            tpflow.setResId("[政务超市]1024");
            tpflow.setAuditOpinion(remark);
            approvalAllApi.updateNodeApprovalResults(tpflow, user.getOwnDeptIdList(), user.getRoleIdList());
        }
    }

    @Override
    public IpApplyInfoVo getUserApplyInfo(Integer userId, Integer applyId) throws BizException {
        GsAppIpApply appIpApplyInfo = gsAppIpApplyMapper.selectOne(Wrappers.<GsAppIpApply>lambdaQuery().eq(GsAppIpApply::getId, applyId));
        Assert.isNull(appIpApplyInfo, "找不到该订单信息");
        // 获取自建系统信息
        GsApp appInfo = gsAppService.getOne(Wrappers.<GsApp>lambdaQuery().eq(GsApp::getId, appIpApplyInfo.getAppId()));
        List<GsIpChange> ipList = gsIpChangeService.list(Wrappers.<GsIpChange>lambdaQuery()
                .in(GsIpChange::getId, Arrays.asList(appIpApplyInfo.getIpId().split(","))));
        // 根据ipChange的resId查询资源并放入对应的位置
        List<String> resId = ipList.stream().map(GsIpChange::getResIdList).collect(Collectors.toList());
        StringBuilder resIdList = new StringBuilder();
        resId.forEach(id -> {
            resIdList.append(id);
        });
        List<GsRes> resList = gsResService.list(Wrappers.<GsRes>lambdaQuery().in(GsRes::getId, Arrays.asList(new String(resIdList).split(","))));
        // 对比修改列表的资源id列表,如果包含该资源id,就放入资源名称
        ipList.forEach(ipVo -> {
            resList.forEach(res -> {
                if (ipVo.getResIdList().indexOf(res.getId() + "") != -1) {
                    ipVo.getResName().add(res.getName());
                    ipVo.setResIdList(ipVo.getResIdList().replace(res.getName() + "", ""));
                }
            });
        });
        IpApplyInfoVo vo = new IpApplyInfoVo();
        // 获取流程审批模块该订单的节点信息
        List<TpApproveFlow> tpApproveFlows = approvalAllApi.selectApprovalFlowByResId(appIpApplyInfo.getApplyNo());
        List<OrderFlowVO> flowVOS = new ArrayList<>();
        tpApproveFlows.forEach(tp -> {
            flowVOS.add(new OrderFlowVO().setCreateTime(tp.getModifyTime()).setFlowState(tp.getFlowAvailable())
                    .setType(tp.getResult()).setOpUserNameId(tp.getModifyUser()).setOpinion(tp.getAuditOpinion()).setOpUserDeptId(tp.getApprovalDeptId()));
        });
        // 查询出所有节点信息的部门信息,放入需要当前节点将有那个部门审核的部门名称
        List<DeptDto> deptDtos = userQueryApi.listDeptByIds(tpApproveFlows.stream().map(TpApproveFlow::getApprovalDeptId).collect(Collectors.toList()));
        for (DeptDto deptDto : deptDtos) {
            for (OrderFlowVO flowVo : flowVOS) {
                if (deptDto.getId().equals(flowVo.getOpUserDeptId())) {
                    flowVo.setOpUserDept(deptDto.getName());
                }
            }
        }
        // 查询出所有节点信息的审批人信息,放入需要节点信息中
        List<UserDTO> userDTOS = userQueryApi.listUser(tpApproveFlows.stream().map(TpApproveFlow::getModifyUser).collect(Collectors.toList()));
        for (UserDTO userDto : userDTOS) {
            for (OrderFlowVO flowVo : flowVOS) {
                if (userDto.getId().equals(flowVo.getOpUserNameId())) {
                    flowVo.setOpUserName(userDto.getName());
                }
            }
        }
        vo.setFlowList(flowVOS);
        // 放入最新的节点信息以此判断是否需要审核
        List<TpApproveFlow> newFlowInfo = tpApproveFlows.stream().filter(flow -> flow.getResult() == 1 || flow.getResult() == 3).collect(Collectors.toList());
        if (newFlowInfo.size() != 0) {
            vo.setFlowResult(newFlowInfo.get(0).getResult());
        } else {
            vo.setFlowResult(3);
        }
        vo.setApplyId(applyId);
        vo.setAppName(appInfo.getName());
        vo.setAppCode(appInfo.getCode());
        vo.setDescription(appInfo.getDescription());
        vo.setIpList(ipList);
        return vo;
    }

}
